<!-- ERP 产品的新增/修改 -->
<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="条码" prop="barCode">
            <el-input v-model="formData.barCode" placeholder="请输入条码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="品目" prop="categoryId">
            <el-tree-select
              v-model="formData.categoryId"
              :data="categoryList"
              :props="defaultProps"
              check-strictly
              default-expand-all
              placeholder="请选择品目"
              class="w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="品类" prop="unitId">
            <el-select v-model="formData.unitId" clearable placeholder="请选择品类" class="w-1/1">
              <el-option
                v-for="unit in unitList"
                :key="unit.id"
                :label="unit.name"
                :value="unit.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="金成色" prop="goldFineness">
            <el-select
              v-model="formData.goldFineness"
              clearable
              placeholder="请选择金成色"
              class="w-1/1"
            >
              <el-option
                v-for="item in goldFinenessList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="库存数量" prop="stock">
            <el-input-number
              v-model="formData.stock"
              placeholder="请输入库存数量"
              :min="0"
              :precision="0"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品来源" prop="productSource">
            <el-select
              v-model="formData.productSource"
              clearable
              placeholder="请选择商品来源"
              class="w-1/1"
            >
              <el-option
                v-for="item in productSourceList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :value="0">上架</el-radio>
              <el-radio :value="1">下架</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规格" prop="standard">
            <el-input v-model="formData.standard" placeholder="请输入规格" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="保质期天数" prop="expiryDay">
            <el-input-number
              v-model="formData.expiryDay"
              placeholder="请输入保质期天数"
              :min="0"
              :precision="0"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="重量（g）" prop="weight">
            <el-input-number
              v-model="formData.weight"
              placeholder="请输入重量（g）"
              :min="0"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="采购价格" prop="purchasePrice">
            <el-input-number
              v-model="formData.purchasePrice"
              placeholder="请输入采购价格，单位：元"
              :min="0"
              :precision="2"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="销售价格" prop="salePrice">
            <el-input-number
              v-model="formData.salePrice"
              placeholder="请输入销售价格，单位：元"
              :min="0"
              :precision="2"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最低价格" prop="minPrice">
            <el-input-number
              v-model="formData.minPrice"
              placeholder="请输入最低价格，单位：元"
              :min="0"
              :precision="2"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 新增字段：图片和工艺相关 -->
      <el-divider content-position="left">产品图片与工艺</el-divider>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="产品图片" prop="imageUrl">
            <el-upload
              class="image-uploader"
              :http-request="httpRequest"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :before-upload="beforeImageUpload"
              accept="image/*"
            >
              <img v-if="formData.imageUrl" :src="formData.imageUrl" class="image-preview" />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">支持 jpg、png、gif 格式，文件大小不超过 2MB</div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="整体工艺" prop="overallCraftsmanship">
            <el-select
              v-model="formData.overallCraftsmanship"
              clearable
              placeholder="请选择整体工艺"
              class="w-1/1"
            >
              <el-option label="5D" value="5D" />
              <el-option label="5G" value="5G" />
              <el-option label="3D" value="3D" />
              <el-option label="倒模" value="倒模" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="表面工艺" prop="surfaceCraftsmanship">
            <el-select
              v-model="formData.surfaceCraftsmanship"
              clearable
              placeholder="请选择表面工艺"
              class="w-1/1"
            >
              <el-option label="古法" value="古法" />
              <el-option label="抛光" value="抛光" />
              <el-option label="珐琅" value="珐琅" />
              <el-option label="拉丝" value="拉丝" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="塑形工艺" prop="shapingCraftsmanship">
            <el-select
              v-model="formData.shapingCraftsmanship"
              clearable
              placeholder="请选择塑形工艺"
              class="w-1/1"
            >
              <el-option label="实心" value="实心" />
              <el-option label="厚壁中空" value="厚壁中空" />
              <el-option label="镂空" value="镂空" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 新增字段：尺寸相关 -->
      <el-divider content-position="left">产品尺寸</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="面宽(mm)" prop="faceWidth">
            <el-input-number
              v-model="formData.faceWidth"
              placeholder="请输入面宽"
              :min="0"
              :precision="2"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="圈口/内径(mm)" prop="innerDiameter">
            <el-input-number
              v-model="formData.innerDiameter"
              placeholder="请输入圈口/内径"
              :min="0"
              :precision="2"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 新增字段：配件和特殊要求 -->
      <el-divider content-position="left">配件与特殊要求</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="配件" prop="accessories">
            <el-select
              v-model="formData.accessories"
              clearable
              multiple
              placeholder="请选择配件"
              class="w-1/1"
            >
              <el-option label="莫桑" value="莫桑" />
              <el-option label="锆石" value="锆石" />
              <el-option label="钻石" value="钻石" />
              <el-option label="珍珠" value="珍珠" />
              <el-option label="翡翠" value="翡翠" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="特殊要求" prop="specialRequirements">
            <el-input v-model="formData.specialRequirements" placeholder="请输入特殊要求" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { ProductCategoryApi, ProductCategoryVO } from '@/api/erp/product/category'
import { CommonStatusEnum } from '@/utils/constants'
import { defaultProps, handleTree } from '@/utils/tree'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { Plus } from '@element-plus/icons-vue'
import { useUpload } from '@/components/UploadFile/src/useUpload'

/** ERP 产品 表单 */
defineOptions({ name: 'ProductForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined as number | undefined,
  name: undefined as string | undefined,
  barCode: undefined as string | undefined,
  categoryId: undefined as number | undefined,
  unitId: undefined as number | undefined,
  goldFineness: undefined as number | undefined,
  stock: 0 as number,
  productSource: undefined as number | undefined,
  status: undefined as number | undefined,
  standard: undefined as string | undefined,
  remark: undefined as string | undefined,
  expiryDay: undefined as number | undefined,
  weight: undefined as number | undefined,
  purchasePrice: undefined as number | undefined,
  salePrice: undefined as number | undefined,
  minPrice: undefined as number | undefined,
  // 新增字段
  imageUrl: undefined as string | undefined,
  overallCraftsmanship: undefined as string | undefined,
  surfaceCraftsmanship: undefined as string | undefined,
  shapingCraftsmanship: undefined as string | undefined,
  faceWidth: undefined as number | undefined,
  innerDiameter: undefined as number | undefined,
  accessories: undefined as string | undefined,
  specialRequirements: undefined as string | undefined
})
const formRules = reactive({
  name: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
  barCode: [{ required: true, message: '产品条码不能为空', trigger: 'blur' }],
  categoryId: [{ required: true, message: '产品品目编号不能为空', trigger: 'blur' }],
  unitId: [{ required: true, message: '品类编号不能为空', trigger: 'blur' }],
  goldFineness: [{ required: true, message: '金成色不能为空', trigger: 'blur' }],
  stock: [{ required: true, message: '库存数量不能为空', trigger: 'blur' }],
  productSource: [{ required: true, message: '商品来源不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '产品状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const categoryList = ref<ProductCategoryVO[]>([]) // 产品品目列表
const unitList = ref<ProductCategoryVO[]>([]) // 产品品类列表
const goldFinenessList = ref<ProductCategoryVO[]>([]) // 金成色列表
const productSourceList = ref<ProductCategoryVO[]>([]) // 商品来源列表

// 图片上传相关
const { httpRequest } = useUpload('product')

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProductApi.getProduct(id)
    } finally {
      formLoading.value = false
    }
  }
  // 产品品目 - 查询ID为1的品目的子项目
  const categoryData = await ProductCategoryApi.getProductCategoryChildren(1)
  categoryList.value = handleTree(categoryData, 'id', 'parentId')
  // 产品品类 - 查询ID为2的品类的子项目
  const unitData = await ProductCategoryApi.getProductCategoryChildren(2)
  unitList.value = unitData
  // 金成色 - 查询ID为3的子项目
  const goldFinenessData = await ProductCategoryApi.getProductCategoryChildren(3)
  goldFinenessList.value = goldFinenessData
  // 商品来源 - 查询ID为13的子项目
  const productSourceData = await ProductCategoryApi.getProductCategoryChildren(13)
  productSourceList.value = productSourceData
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ProductVO
    if (formType.value === 'create') {
      await ProductApi.createProduct(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProductApi.updateProduct(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    barCode: undefined,
    categoryId: undefined,
    unitId: undefined,
    goldFineness: undefined,
    stock: 0,
    productSource: undefined,
    status: CommonStatusEnum.ENABLE,
    standard: undefined,
    remark: undefined,
    expiryDay: undefined,
    weight: undefined,
    purchasePrice: undefined,
    salePrice: undefined,
    minPrice: undefined,
    // 新增字段
    imageUrl: undefined,
    overallCraftsmanship: undefined,
    surfaceCraftsmanship: undefined,
    shapingCraftsmanship: undefined,
    faceWidth: undefined,
    innerDiameter: undefined,
    accessories: undefined,
    specialRequirements: undefined
  }
  formRef.value?.resetFields()
}

// 图片上传相关方法
/** 上传前校验 */
const beforeImageUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    message.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

/** 上传成功回调 */
const handleImageSuccess = (response: any) => {
  if (response.code === 0) {
    formData.value.imageUrl = response.data
    message.success('图片上传成功!')
  } else {
    message.error(response.msg || '图片上传失败!')
  }
}
</script>

<style scoped>
.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.image-uploader:hover {
  border-color: #409eff;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.image-preview {
  width: 178px;
  height: 178px;
  object-fit: cover;
  display: block;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}
</style>
